package com.example.pubsearch;

import java.util.ArrayList;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;

import com.example.pubsearch.db.MySQLiteHelper;

public class SearchActivity extends Activity {
	private ListView lv;
	private ArrayList<String> pubs;
	private EditText et;
	private String listview_array[];
	private ArrayList<String> array_sort = new ArrayList<String>();
	int textlength = 0;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_search);

		MySQLiteHelper dbHelper = new MySQLiteHelper(this);
		pubs = dbHelper.getPubNamesBySearchString("");

		int i = 0;
		listview_array = new String[pubs.size()];
		for (String pub : pubs) {
			listview_array[i] = pub;
			i++;
		}

		lv = (ListView) findViewById(R.id.ListView01);
		et = (EditText) findViewById(R.id.EditText01);
		lv.setAdapter(new ArrayAdapter<String>(this,
				android.R.layout.simple_list_item_1, listview_array));

		lv.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				Intent myIntent = new Intent(view.getContext(),
						DetailActivity.class);
				Bundle b = new Bundle();
				b.putString("pubName", (String) lv.getItemAtPosition(position));
				myIntent.putExtras(b);
				startActivityForResult(myIntent, 0);
			}
		});

		et.addTextChangedListener(new TextWatcher() {
			public void afterTextChanged(Editable s) {
				// Abstract Method of TextWatcher Interface.
			}

			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// Abstract Method of TextWatcher Interface.
			}

			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				textlength = et.getText().length();
				array_sort.clear();
				for (int i = 0; i < listview_array.length; i++) {
					if (textlength <= listview_array[i].length()) {
						if (listview_array[i].toLowerCase().contains(
								et.getText().toString().toLowerCase())) {
							array_sort.add(listview_array[i]);
						}
					}

				}
				lv.setAdapter(new ArrayAdapter<String>(SearchActivity.this,
						android.R.layout.simple_list_item_1, array_sort));
			}
		});
	}
}
